package com.juyu.miliao.api.service;

import com.juyu.miliao.api.dao.mysql.BillDetailDao;
import com.juyu.miliao.api.dao.mysql.UserCashDao;
import com.juyu.miliao.api.dao.mysql.UserInfoDao;
import com.juyu.miliao.api.dao.mysql.UserWalletDao;
import com.juyu.miliao.api.dao.redis.UserRedisDao;
import com.juyu.miliao.api.domain.BillDetailDeposit;
import com.juyu.miliao.api.domain.User;
import com.juyu.miliao.api.domain.UserCash;
import com.juyu.miliao.api.domain.UserWallet;
import com.juyu.miliao.api.domain.dto.IntegralLevelAndTitleDTO;
import com.juyu.miliao.api.domain.vo.UserCashVo;
import com.juyu.miliao.api.exception.WrongErrorMoney;
import com.juyu.miliao.api.util.PageUtil;
import com.juyu.miliao.common.constant.EnumType;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import com.juyu.miliao.common.netease.NetEaseCloudUserService;
import com.juyu.miliao.common.util.DoubleFormatUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserCashService {
	@Resource
	private UserCashDao userCashDao;
	@Resource
	private UserWalletDao userWalletDao;
	@Resource
	private UserRedisDao userRedisDao;
	@Resource
	private UserInfoDao userInfoDao;
	@Resource
	private IntegralLevelInfoService integralLevelInfoService;
    @Resource
    private BillDetailDao billDetailDao;

	private static final long robotSendMessageUserId = 12890000;

	private final Logger logger = LoggerFactory.getLogger(UserCashService.class);

	private static final Map<Integer,Integer> cashNumberMap = new LinkedHashMap<>();

	UserCashService(){
		cashNumberMap.put(1,50);
		cashNumberMap.put(2,100);
		cashNumberMap.put(3,200);
		cashNumberMap.put(4,500);
		cashNumberMap.put(5,1000);
		cashNumberMap.put(6,2000);

	}

	/**
	 * 返回用户账户中可兑换人民币金额
	 * 
	 * @param userId
	 * @return
	 */
	public JSONObject getUserWallet(long userId) {
		JSONObject json = new JSONObject();
		UserWallet userWallet = userWalletDao.getUserWalletById(userId);
		UserCash userCash = userCashDao.getUserCashInfoByUserId(userId);
		if(userCash == null){
            userCash = new UserCash();
		}
		// 获取钻石转换人民币比例
//		Appkey appkey = appKeyService.getAppKeyByKey("cash");
//		double ratio = Double.parseDouble(appkey.getValue());
		// 计算可兑换人民币(人民币=钻石/比例)，doubleFormate保留两位小数
		double money = DoubleFormatUtil.doubleFormate(userWallet.getDiamond() / 100);
//		if(StringUtils.isNotBlank(userCash.getZfbNumber())){
//			StringBuilder sb = new StringBuilder(userCash.getZfbNumber());
//			sb.replace(userCash.getZfbNumber().length()-4,userCash.getZfbNumber().length(),"****");
//			userCash.setZfbNumber(sb.toString());
//		}

		json.put("userId", userId+"");
		json.put("money", money+"");
		json.put("diamond", userWallet.getDiamond()+"");
		json.put("zfbNumber", userCash.getZfbNumber()+"");
		json.put("zfbUserName", userCash.getZfbUserName()+"");
		return json;
	}

	/**
	 * 获取可提现金额列表
	 * @return
	 */
	public JSONArray getCashNumberMap() {
        JSONArray jsonArray = new JSONArray();
        JSONObject json = new JSONObject();
        for(Integer key:cashNumberMap.keySet()){
            json.put("id",key);
            json.put("value",cashNumberMap.get(key));
            jsonArray.add(json);
        }
		return jsonArray;
	}



	/**
	 * 用户提现请求
	 * @param entity
	 */
	@Transactional(rollbackFor = Exception.class)
	public void submitUserCash(UserCash entity) {
		User user  = userInfoDao.selectAdminByUnionId(entity.getUserId());
		if(user == null || user.getIsHost() != 1){
			throw new ConsumeRuntimeException("只有主播可以提交提现申请");
		}
        if (userRedisDao.isMemberUserCashEveryDayNumber(entity.getUserId())) {
            throw new ConsumeRuntimeException("今日提现次数已过");
        }
		Integer money = cashNumberMap.get(entity.getCashNumberId());
		if(money == null){
            throw new ConsumeRuntimeException("提现金额错误");
        }
		UserCash userCash = userCashDao.getUserCashInfoByUserId(entity.getUserId());
		if(userCash == null){
			throw new ConsumeRuntimeException("提现基础信息错误");
		}
		// 判断 金额是否大于最大可兑换的人民币数值
		UserWallet userWallet = userWalletDao.getUserWalletById(entity.getUserId());
		double moneySum = DoubleFormatUtil.doubleFormate(userWallet.getDiamond() / 100);
		if (moneySum < money)
			throw new WrongErrorMoney();
		// 计算要兑换的钻石数
		double diamond = DoubleFormatUtil.doubleFormate(money*100);
		// 减去用户账户钻石
		userWallet.setDiamond(diamond);
		userWalletDao.minusDiamond(userWallet);

		String orderId ="CYDDH"+System.currentTimeMillis();
		// 保存提现请求
		entity.setDiamond(diamond);
		entity.setCashId(orderId);
		entity.setType(1);
		//扣除2%手续费
		entity.setMoney(DoubleFormatUtil.doubleFormate(money-money*0.02));
		entity.setZfbNumber(userCash.getZfbNumber());
		entity.setZfbUserName(userCash.getZfbUserName());
		entity.setUnionId(user.getUnionId());
		entity.setNickName(user.getNickName());
		entity.setAdminId(user.getAdminId());
		IntegralLevelAndTitleDTO integralLevelAndTitleDTO = integralLevelInfoService
				.getUserIntegralLevel(user.getIntegralSum());
		int integralGrade = 1;
		if(integralLevelAndTitleDTO != null){
			integralGrade = integralLevelAndTitleDTO.getIntegralGrade();
		}
		entity.setIntegralGrade(integralGrade);
		userCashDao.insertUserCash(entity);
        userRedisDao.addUserCashEveryDayNumber(entity.getUserId());

        BillDetailDeposit billDetailDeposit = new BillDetailDeposit();
        billDetailDeposit.setRecordType(4);
        billDetailDeposit.setInUserId(0);
        billDetailDeposit.setOutUserId(entity.getUserId());
        billDetailDeposit.setSpend(0);
        billDetailDeposit.setDiamond(-diamond);
        billDetailDeposit.setRatio(0);
        billDetailDeposit.setUnionId(user.getUnionId());

		billDetailDeposit.setAdminId(user.getAdminId());
        billDetailDao.insertBillDetailDeposit(billDetailDeposit);

//		userCashSystemMessage(entity.getUserId(),money);
	}

	public List<UserCashVo> getUserCashList(long userId, Integer page, Integer pageSize) {
		int startNum = PageUtil.getOffset(page, pageSize);
		List<UserCashVo> list = userCashDao.getUserCashList(userId,startNum,pageSize);
		//类型：1运营待审核，2财务待审核，3待打款，4审核通过 5运营审核未通过 6财务审核未通过
		//修改后 1：审核中 2：审核通过 3审核未通过
		list.forEach(i -> {
			switch (i.getType()){
				case "1":
					break;
				case "2":
					i.setType("1");
					break;
				case "3":
					i.setType("1");
					break;
				case "4":
					i.setType("2");
					break;
				case "5":
					i.setType("3");
					break;
				case "6":
					i.setType("3");
					break;
			}
		});
		return list;
	}

	/**
	 * 提现系统消息
	 * @param userId
	 * @param money
	 */
	private void userCashSystemMessage(long userId,double money){
		Date t = new Date();
		SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日HH:mm");
		String dateTime =df.format(t);
		String message = "您于"+dateTime+"成功发起提现申请，"
							+"提现人名币"+money+"元，请耐心等待审核，如有问题请联系官方客服ID：11241600";
		JSONObject body = new JSONObject();
		body.put("msg", message);
		//开发者扩展字段
		JSONObject ext = new JSONObject();
		try {
			String temp = NetEaseCloudUserService.getSendMsg(userId,robotSendMessageUserId,
					EnumType.TEXT_MESSAGE.state, body.toString(),ext.toString(),"");
			if (!temp.substring(temp.indexOf("code") + 6, temp.indexOf("code") + 9).equals("200"))
				if(logger.isInfoEnabled()){
					logger.info("提现系统消息发送IM失败：系统错误信息:temp={},参数：userId={}",temp,userId);
				}
		} catch (Exception e) {
			logger.error("提现系统消息发送IM错误", e);
		}
	}


	public void insertUserCashInfo(UserCash entity) {
		userCashDao.insertUserCashInfo(entity);
	}
}
